package concat

import (
	"errors"
	"log"
)

var (
	ErrFileNotExist    = errors.New("file does not exist")
	ErrContentNotExist = errors.New("file content does not exist")
	ErrFileType        = errors.New("file type inconsistent")
)

type ConcatFile struct {
	FilePath []string
}

func NewConcatFile(staticPath, rawFileName, sep string, unique, compatible bool) (ConcatFile, error) {
	c := ConcatFile{}
	filename := ParseFileName(rawFileName, sep, compatible)
	filepath := GetFilePath(staticPath, filename)
	if len(filepath) == 0 {
		return c, ErrFileNotExist
	}
	if unique {
		if len(mimeTypes(filename)) > 1 {
			return c, ErrFileType
		}
	}
	c.FilePath = filepath
	return c, nil
}

// 分别读取文件内容，并且组合返回
func (c *ConcatFile) Content() (contents []byte, err error) {
	for _, filepath := range c.FilePath {
		content, err := ReadFile(filepath)
		if err == nil {
			contents = append(contents, content...)
		} else {
			log.Printf("read file fail, error info: %s", err)
		}
	}

	if contents == nil {
		return nil, ErrContentNotExist
	}
	return contents, nil
}
